package vip.aster.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * 查询Ip所在地理位置
 *
 * @author Aster
 * @since 2023/11/16 17:22
 */
@Slf4j
public class AddressUtils {
    /**
     * IP地址查询
     */
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    /**
     * 未知地址
     */
    public static final String UNKNOWN = "XX XX";

    private static final String EXCEPTION_MESSAGE = "获取地理位置异常 {}";

    public static String getRealAddressByIp(String ip) {
        String url = IP_URL + "?ip=" + ip + "&json=true";
        String address = UNKNOWN;
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        try {
            String rspStr = HttpUtil.get(url, Charset.forName("GBK"));
            if (StrUtil.isBlank(rspStr)) {
                log.error(EXCEPTION_MESSAGE, ip);
                return UNKNOWN;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            address = String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error(EXCEPTION_MESSAGE, e.getMessage());
        }

        return address;
    }

}
